package server;

import static server.ConnectionServer.requestChannel;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class GpcResponseProcessor {

	//构造线程池
	private static ExecutorService  executorService  = Executors.newFixedThreadPool(10);

	public static void ProcessorRespone(final SelectionKey key) {
		//获得线程并执行
		executorService.submit(new Runnable() {

			@Override
			public void run() {
				try {
					// 写操作
					SocketChannel writeChannel = (SocketChannel) key.channel();
					//拿到客户端传递的数据
					//ByteArrayOutputStream attachment = (ByteArrayOutputStream)key.attachment();

					//System.out.println("客户端发送来的数据："+new String(attachment.toByteArray()));
					System.out.println("正在注册写操作");
					ByteBuffer buffer = ByteBuffer.allocate(1024);
					if(true) {
						BlockingQueue<GpcRequest> receiver = requestChannel.get(key.attachment());
						if(receiver==null) {
							Thread.sleep(1);
							return;
						}
						GpcRequest message = receiver.poll(100, TimeUnit.MILLISECONDS);
						if(message==null) {
							Thread.sleep(1);
							return;
						}
						while(message!=null) {
							//System.out.println("开始写"+message+",剩余："+receiver.size()+"消息");
							buffer.clear();
							buffer.put(serialize(message));
							buffer.flip();
							writeChannel.write(buffer);
							message = receiver.poll(1000, TimeUnit.MILLISECONDS);
						}
					}
					//ConnectionServer.reReader(key);
				} catch (IOException | InterruptedException e) {
					e.printStackTrace();
				}       
			}
		});
	}
	
	/**
	 * 将byte[] -->Object
	 * @param bytes
	 * @return
	 */
	private static byte[] serialize(Object request) {
		ByteArrayOutputStream bais = null;
		try {
			// 反序列化
			bais = new ByteArrayOutputStream();
			ObjectOutputStream ois = new ObjectOutputStream(bais);
			ois.writeObject(request);
			return bais.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
			//logger.error("{}", e);
		} finally {
			try {
				bais.close();
			} catch (IOException e) {
				//logger.error("{}", e);
			}
		}
		return null;
	}

}
